const _ = require('lodash');
const Utils = require("../../utils/index");
const { PARAM_ERROR } = require("../../config/admin/state_code");

module.exports = app => {
  return class AppController extends app.Controller {
    async index() {
      let {ctx} = this;
      if(ctx.session.id){
        ctx.redirect("/")
      }
      await ctx.render('admin/login.js',{
        title:'后台登录'
      })
    }

    async login() {
      const {ctx} = this;
      let Rs =  await ctx.service.user.login(ctx.request.body);
      if(Rs.error_code === 0){
         ctx.session = Rs.data
      }
      ctx.body = Rs;
    }

    async loginOut() {
      const {ctx} = this;
      ctx.session = null;
      ctx.redirect('/login');
    }

    async registerUser(){
      const {ctx} = this;
      let Rs = await ctx.service.user.register(ctx.request.body);
      ctx.body = Rs;
    }


    async getNormalUsers (){
      const {ctx} = this;
      let size = ctx.request.body.size || 5 ,
          filter = ctx.request.body.filter || {},
          page = ctx.request.body.page || 1;
      if(page){
        let Rs = await ctx.service.user.getNormalUsers(page,size,filter);
        ctx.body = Rs;
      }else{
        ctx.body =  Utils.createServerMsg("page不存在",PARAM_ERROR,"");
      }
    }

    async delUser (){
      const {ctx} = this;
      let id = ctx.request.body.id;
      if(!id) return ctx.body = Utils.createServerMsg("id不存在",PARAM_ERROR,"");
      let Rs = await  ctx.service.user.delUser(id);
      ctx.body = Rs;
    }

    async editUserPassWord(){
      const {ctx} = this;
      let id = ctx.request.body.id;
      let password = ctx.request.body.password;
      if(!id || !password){
        return ctx.body = Utils.createServerMsg("参数错误",PARAM_ERROR,"");
      }
      let Rs = await ctx.service.user.editUserPassWord(id,password);
      ctx.body = Rs;
    }
  };
};

